<?php

namespace Database\Seeders\Commands;

use Illuminate\Database\Seeder;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Str;


/**
 * 定时清理备份数据
 */
class DelBackupSeeder extends Seeder
{
    protected $disk = null; //备份数据磁盘

    protected $del_prefix = ''; //要删除的文件前缀

    protected $recent_month_num = 2; //保留最近1个月数据

    /**
     * Run the database seeds.
     *
     * @return void
     */
    public function run()
    {
        $date = now()
            ->subMonth($this->recent_month_num)
            ->format('Y-m');
        $dir = 'laravel-backup/';
        $this->disk = Storage::disk('local');
        $files = $this->disk->allFiles($dir);
        $this->del_prefix = $dir.$date;
        collect($files)->each(function ($file){
            if(Str::startsWith($file,$this->del_prefix)){
                $res = $this->disk->delete($file);
                if($res!==false){
                    $this->command->info("成功删除文件:{$file}");
                }
            }
        });
    }
}
